#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"

from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import HttpResponse
from repoistory import models
from django.http import Http404
from ..libs.forms import HostCreateForm
from ..libs.forms import HostEditForm


def preview(request):
    '''服务器表总览'''
    if request.method == 'GET':
        res_dict = {'query_set':models.Host.objects.values('id','ip_address','description').all()}
        return render(request, 'backend/Host/preview.html', res_dict)
    
    
def add(request):
    '''新增服务器'''
    if request.method == 'GET':
        form_obj = HostCreateForm()
    if request.method == 'POST':
        form_obj = HostCreateForm(request.POST)
        if form_obj.is_valid():
            models.Host.objects.create(**form_obj.cleaned_data)
            return redirect('/backend/Host/preview/')

    res_dict = {'form_obj': form_obj}
    return render(request, 'backend/Host/change.html', res_dict)


def change(request,nid):
    '''修改服务器'''
    host_obj = models.Host.objects.filter(id=nid).first()
    if not host_obj:
        raise Http404
    if request.method == 'GET':
        initial = {'id': host_obj.id,
                   'ip_address':host_obj.ip_address,
                   'ssh_port': host_obj.ssh_port,
                   'ssh_user': host_obj.ssh_user,
                   'ssh_password': host_obj.ssh_password,
                   'description': host_obj.description,}
        form_obj = HostEditForm(initial=initial)
    elif request.method == 'POST':
        form_obj = HostEditForm(request.POST)
        if form_obj.is_valid():
            print(form_obj.cleaned_data.items())
            for field, value in form_obj.cleaned_data.items():
                print(field, value)
                setattr(host_obj,field,value)
                host_obj.save()
            return redirect('/backend/Host/preview/')
    res_dict = {'form_obj': form_obj}
    return render(request, 'backend/Host/change.html', res_dict)